package data;

import database.DataBaseConnection;
import entity.Userinfo;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ValidateLoginInfo {
    private String username;
    private String password;
    private static Logger logger = Logger.getLogger(ValidateLoginInfo.class);

    public ValidateLoginInfo(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public JSONObject validate() {
        Connection connection = DataBaseConnection.getConnection();
        JSONObject jsonObject = new JSONObject();
        if (connection != null) {
            String sql = "select * from userinfo where username = ? and password = PASSWORD('" + password + "')";
            try {
                PreparedStatement preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1, this.username);
                ResultSet resultSet = preparedStatement.executeQuery();
                if (resultSet != null && resultSet.next()) {
                    int id = resultSet.getInt("id");
                    String operator = resultSet.getString("operator");
                    jsonObject.put("result", true);
                    jsonObject.put("id", id);
                    jsonObject.put("operator", operator);
                    Userinfo userinfo = new Userinfo(id, username, operator);
                    UserInfoList.addUser(userinfo);
                    logger.info("新的登录用户: " + id + " " + username + " " + operator);
                    UserInfoList.outUserInfo();
                } else {
                    jsonObject.put("result", false);
                }
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            DataBaseConnection.closeConnection(connection);
        }
        return jsonObject;
    }
}
